package sddz.foodmanage.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.model.UserStatusBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;

/**
 * @Date:2019/7/2
 * @Author:lbb
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.iv_login)
    ImageView ivLogin;
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.image_user)
    ImageView imageUser;
    @BindView(R.id.et_login_passs)
    EditText etLoginPasss;
    @BindView(R.id.iv_pass_setting)
    CheckBox ivPassSetting;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.activity_login)
    AutoLinearLayout activityLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();
        initListener();
    }

    private void initListener() {

        /**
         * 当edittext内容发生变化时，删除显示
         */
        MyUtils.EditextChange(etLoginName, imageUser);

    }

    private void initView() {
        titleNavigationIcon.setVisibility(View.GONE);
        titleText.setText("登录");
        if(SpfUtils.getUserData(mActivity)!=null){
            String name=SpfUtils.getUserData(mActivity).getName();
            etLoginName.setText(name);
        }
    }

    /**
     * 是否显示密码
     */
    private void isShowPassWord() {
        boolean checked = ivPassSetting.isChecked();
        if (checked) {
            etLoginPasss.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            etLoginPasss.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        //切换后将EditText光标置于末尾
        CharSequence charSequence = etLoginPasss.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    @OnClick({R.id.tv_login, R.id.image_user,R.id.iv_pass_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login://登录按钮
                login();
//                startActivity(new Intent(mActivity, MainNewActivity.class));
//                finish();
                break;
            case R.id.image_user:
                etLoginName.setText("");
                imageUser.setVisibility(View.GONE);
                break;
            case R.id.iv_pass_setting:
                isShowPassWord();
                break;
        }
    }

    /**
     * 登录的方法
     */
    private void login() {
        final String idNumber = etLoginName.getText().toString();
        final String pass = etLoginPasss.getText().toString();

        if (TextUtils.isEmpty(idNumber.trim())) {
            show("身份证号不能为空");
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            show("密码不能为空");
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("name", idNumber);
        params.put("password", pass);
        dialog.setMessage("正在登录...");
        dialog.show();
        Log.e("params",params.toString());
        HttpUtils.getInstance().POST(mActivity, API.getLogin, JSON.toJSONString(params), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();
                Log.e("ssss", body);
                if (!TextUtils.isEmpty(body)) {
                    if(body.contains("html")) {
                        show("登录失败，请联系管理员");
                    }else {
                        UserStatusBean userStatusBean = new Gson().fromJson(body, UserStatusBean.class);
                        if (userStatusBean.getStatus_code() == 200) {
                            show("登录成功");
                            //保存用户信息和token值
                            JPushInterface.setAlias(mActivity, String.valueOf(userStatusBean.getData().getUser().getUser_id()),
                                    new TagAliasCallback() {
                                        @Override
                                        public void gotResult(int arg0, String arg1, Set<String> arg2) {
                                            Log.e("JP", "setAlias " + arg0);
                                            if (arg0 == 0) {

                                            }
                                        }
                                    });
                            SpfUtils.setUserData(mActivity, userStatusBean.getData().getUser());
                            SpfUtils.savetoken(mActivity, userStatusBean.getData().getToken());
                            Log.e("token", SpfUtils.gettoken(mActivity));
                            SpfUtils.setLogin(mActivity, true);
                            startActivity(new Intent(mActivity, MainNewActivity.class));
                            finish();
                        } else {
                            show(userStatusBean.getMessage());
                        }
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
                Log.e("ssss", e.toString());
                show("访问数据失败，请稍后重试");
            }
        });

    }
}
